import {
  HOST
} from '../config';

const axios = (url, data = {}, type = "post", config = {}) => {

  wx.showLoading({
    title: '加载中...',
  })

  let header = {
    "Content-Type": "application/x-www-form-urlencoded"
  };

  let token = getApp().globalData.userToken
  if (token) {
    header['X-TOKEN'] = token;
  }

  return new Promise(function (resolve, reject) {
    wx.request({
      url: HOST + url,
      data: data,
      method: type,
      header: Object.assign({}, header, config),
      success: function (res) {
        // 502或token过期后，修正状态重新请求
        if (res.statusCode == 502 || res.data.resultcode == 3) {
          if (res.data.resultcode == 3) {
            getApp().globalData.userToken = ''
            wx.removeStorageSync("userToken");
          }
          axios(url, data, type, config).then(reset => {
            resolve(reset);
          });
        } else if (res.data.resultcode == 0 && res.data.message == "请登录") {
          // 需要登录的时候不返回，在事件委托那弹出授权框
          getApp().globalData.showLogin = true
        } else {
          resolve(res);
        }
        wx.hideLoading();
      },
      fail: function (err) {
        console.log("请求失败，重新请求", err);
      }

    })
  })

};

module.exports = axios